package cn.ztydata.teachingsystem.heaven.dao.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 教学日志回复量
 *
 * @author lyj
 * @since 2015/5/6
 */
@Repository
public class DailyComCountDao  {

    @Resource(name = "stringRedisTemplate")
    protected RedisTemplate redisTemplate; //sdr-Redis模版

    protected static Logger logger = LoggerFactory.getLogger(DailyComCountDao.class); //日志记录器

    public static final String DAILY_COUNT = "daily:total";

    public static final String DAILY_COMMENT_COUNT = "dailyCommentCount"; //回复量

    /**
     * 递增日志回复量
     *
     * @param dailyId 日志ID
     * @param filed 字段名称
     * @return Long
     * @author lyj
     * @since 2015-5-6
     */
    public Long increment(final long dailyId, final String filed) {
        //获取hash操作
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();

        return hashOperations.increment(KeyUtils.generateKey(DAILY_COUNT, dailyId), filed, 1);

    }


    /**
     * 递减日志回复量
     *
     * @param dailyId 日志ID
     * @param filed 字段名称
     * @return Long
     * @author lyj
     * @since 2015-5-6
     */
    public Long subIncrement(final long dailyId, final String filed) {
        //获取hash操作
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();

        if (getCount(dailyId, DAILY_COMMENT_COUNT) == 0) {
            return Long.valueOf(0);
        }

        return hashOperations.increment(KeyUtils.generateKey(DAILY_COUNT, dailyId), filed, -1);

    }



    /**
     * 获取日志回复量
     *
     * @param dailyId 日志ID
     * @param filed 字段名称
     * @return Long
     * @author lyj
     * @since 2015-5-6
     */
    public Long getCount(final long dailyId, final String filed){
        //获取hash操作
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();

        String count = hashOperations.get(KeyUtils.generateKey(DAILY_COUNT, dailyId), filed);

        logger.debug("获取日志回复量");
        return count == null ? 0 : Long.valueOf(count);
    }
}
